<template>
  <a-modal class="business-modal" :title="isEdit ? '修改附件' : '新增附件'" :width="800" v-model="visible">
    <a-form class="edit-people-form" :form="form">
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" class="name-label" label="附件类型">
        <a-select
          v-decorator="['accessoryType', { rule: [{required: true, message: '请选择附件类型'}], validateTrigger: 'change' }]"
          class="w330"
          placeholder="请选择"
          allowClear
          :getPopupContainer="triggerNode => triggerNode.parentNode"
        >
          <a-select-option
            v-for="item in accessoryTypeArr"
            :key="item.value"
            :value="item.value"
          >{{ item.title }}</a-select-option>
        </a-select>
      </a-form-item>

      <!-- <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" class="name-label" label="附件名称">
        <a-input
          class="w330"
          placeholder="请输入"
          v-decorator="['accessoryName', { rules: [{required: true, message: '请输入附件名称'}], validateTrigger: 'change' }]"
        />
      </a-form-item>-->
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="结束时间">
        <a-date-picker
          class="w330"
          @change="dateChange"
          v-decorator="['date', { rules: [{required: true, message: '请选择结束时间'}], validateTrigger: 'change' }]"
        />
      </a-form-item>
      <a-upload
        listType="picture-card"
        :fileList="fileList"
        class="avatar-uploader"
        :beforeUpload="beforeUpload"
        @preview="handlePreview"
        @change="info => handleChange(info, 3)"
        :customRequest="customRequest"
      >
        <div>
          <a-icon size="large" type="plus" />
          <div class="ant-upload-text">点击上传</div>
        </div>
      </a-upload>
      <preview-modal ref="previewModal" />
    </a-form>
    <!-- <a-divider /> -->
    <div slot="footer" style="text-align: center">
      <a-button size="large" @click="handleCancel">取消</a-button>
      <a-button
        :disabled="fileList.length === 0"
        size="large"
        type="primary"
        :loading="confirmLoading"
        @click.stop="handleOk"
      >{{ isEdit ? '修改' : '新增' }}</a-button>
    </div>
  </a-modal>
</template>

<script>
import { saveOnlyUploads, insertSupplierAccessory } from '@/api/supplier'
import { openNotification, getSession, getDicData, getBase64 } from '@/utils/util'
import PreviewModal from '@/components/PreviewModal'
import pick from 'lodash.pick'

export default {
  components: {
    PreviewModal
  },
  data() {
    return {
      imageUrl: '',
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      visible: false,
      isEdit: false,
      form: this.$form.createForm(this),
      confirmLoading: false,
      mdl: {},
      fileList: [],
      fileArr: [],
      dateArr: null, // 存储时间
      record: {},
      accessoryTypeArr: [],
      saveData: []
    }
  },
  mounted() {
    if (JSON.stringify(this.$route.params) !== '{}') {
      console.log('if')
      this.record = this.$route.params.obj
    } else {
      console.log('else')
      this.record = Object.assign({}, getSession('record'))
    }
    this.accessoryTypeArr = getDicData('002', '002005')
  },
  methods: {
    edit(bool, record) {
      console.log('edit', bool, record)
      this.form.resetFields()
      this.isEdit = bool
      this.mdl = Object.assign({}, record)
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.mdl, 'accessoryType', 'accessoryName', 'date'))
      })
      this.visible = true
    },
    async handleOk(e) {
      e.stopPropagation()
      const {
        form: { validateFields },
        isEdit,
        dateArr
      } = this
      this.confirmLoading = true

      validateFields(['accessoryType', 'date'], { force: true }, async (err, values) => {
        if (!err) {
          console.log('values', values)
          const { accessoryType, date } = values
          const validityBeginDate = null
          const validityEndDate = dateArr
          // console.log('accessoryTypeArr', this.accessoryTypeArr.filter(v => v.key === accessoryType)[0].title)
          // const name = this.accessoryTypeArr.filter(v => v.key === accessoryType)[0].title
          // let paramArr = []
          const param = { accessoryType, validityBeginDate, validityEndDate, createTime: new Date() }
          this.fileArr.map(v => {
            this.saveData.push({ ...param, uploadId: v.uploadId, savePath: v.fileUrl + v.fileName })
          })
          console.log('saveData', this.saveData)
          this.visible = false
          this.$emit('refresh', this.saveData)
          this.fileList = []
          this.fileArr = []
          this.saveData = []
        }
        this.confirmLoading = false
      })
    },
    handleCancel() {
      this.visible = false
    },
    // 预览图片，显示大图
    handlePreview(file) {
      this.$refs.previewModal.show([file.url])
    },
    handleChange(info, arr) {
      console.log('info', info, arr)
      this.imgInfo = info
      this.fileList = info.fileList
      if (info.file.status === 'uploading') {
        this.loading = true
        return
      }
      if (info.file.status === 'done') {
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, imageUrl => {
          this.imageUrl = imageUrl
          console.log('info', info, arr, imageUrl)

          this.loading = false
        })
      }
    },
    handleRemove(info) {
      console.log('remove info', info)
      // 调用删除图片的接口方法
      deleteUploadPic(id).then(res => {
        console.log('remove res', res)
        if (res.state === '000000') {
          openNotification('success', '删除成功')
        }
      })
    },
    // 覆盖原本的上传方法
    customRequest(info, local) {
      console.log('customRequest', info)
      const formData = new FormData()
      formData.append('file', info.file)
      // 调方法，post，body 放入 formData
      saveOnlyUploads(formData).then(res => {
        if (res.data !== null) {
          const { data } = res
          this.fileArr.push(data)
          this.fileList.map(v => {
            v.status = 'done'
            v.url = data.fileUrl + data.fileName
          })
          this.fileList = [...this.fileList]
        }
      })
    },
    // date-picker方法
    dateChange(date, dateString) {
      console.log('date-picker', date, dateString)
      this.dateArr = dateString
    }
  }
}
</script>

<style scoped>
.w330 {
  width: 330px;
}
.avatar-uploader >>> .ant-upload-list-item {
  width: 180px;
  height: 180px;
  display: inline-block;
}
.avatar-uploader >>> .ant-upload {
  width: 180px;
  height: 180px;
}
</style>
